<template>
  <div style="margin-bottom: 10px">
    <span style="font-size: 25px;font-weight: bold;justify-content: center">货物报损界面</span>
  </div>

  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入药品名称进行查询" style="width: 200px" v-model="data.productName"></el-input>
      <el-button type="primary" plain style="margin-left: 10px" @click="load()">查询</el-button>
      <el-button type="warning"  style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <div class="table">
        <el-table :data="data.tableData" stripe max-height="450px" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
          <el-table-column prop="productName" label="药品名称" fixed="left"></el-table-column>
          <el-table-column label="药品图片" fixed="left">
            <template #default="scope">
              <el-image
                  :src="scope.row.imageUrl"
                  :preview-src-list="[scope.row.imageUrl]"
                  preview-teleported
                  style="width: 40px; height: 40px; border-radius: 50%"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="药品价格"></el-table-column>
          <el-table-column prop="unit" label="价格单位"></el-table-column>
          <!--          <el-table-column prop="stockQuantity" label="盘点的库存数量"></el-table-column>-->
          <el-table-column prop="currentStock" label="当前库存"></el-table-column>
          <el-table-column prop="description" label="药品描述" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column prop="category" label="药品类别" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column prop="uploadDate" label="上传时间" width="170"></el-table-column>
          <el-table-column label="操作" align="center" width="180" fixed="right">
            <template v-slot="scope">
              <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">货物报损</el-button>

            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              style="margin-top: 5px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="data.pageNum"
              :page-sizes="[3, 5, 10, 15, 20]"
              :page-size="data.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="data.total">
          </el-pagination>
        </div>
      </div>

    </div>
  </div>
  <el-dialog title="请填写报损信息" v-model="data.formVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
    <el-form :model="data.form" label-width="150px" style="padding-right: 50px" :rules="rules" ref="productForm">
      <el-form-item label="药品名称" prop="productName">
        <el-input v-model="data.form.productName" placeholder="药品名称" disabled></el-input>
      </el-form-item>
      <el-form-item label="药品图片" prop="imageUrl">
        <el-image :src="data.form.imageUrl" style="width: 40px; height: 40px; border-radius: 50%"></el-image>
      </el-form-item>
      <el-form-item label="药品类别" prop="category">
        <el-input v-model="data.form.category" placeholder="药品类别" disabled></el-input>
      </el-form-item>
      <el-form-item label="药品价格" prop="price">
        <el-input-number v-model="data.form.price" placeholder="药品价格"  :precision="2" :step="0.01" :min="0" disabled></el-input-number> 元
      </el-form-item>
      <el-form-item label="价格单位" prop="unit">
        <el-input v-model="data.form.unit" placeholder="价格单位" disabled></el-input>
      </el-form-item>
      <el-form-item label="药品描述" prop="description">
        <el-input type="textarea" v-model="data.form.description" placeholder="药品描述" disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="报损数量" prop="quantity">
        <el-input-number v-model="data.form.quantity" placeholder="报损数量" :min="1"  ></el-input-number>
      </el-form-item>
      <el-form-item label="报损原因" prop="reportCause">
        <el-input v-model="data.form.reportCause" placeholder="报损原因" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false" type="danger">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </span>
    </template>
  </el-dialog>

</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'

import {
  deleteBatchSellerProductApi,
  deleteSellerProductApi,
  loadSellerProductApi,
  saveSellerProductApi
} from "@/utils/API/shop/SellerProduct";
import {insertDamageReportApi} from "@/utils/API/demageReport/damageReport";
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
// 定义响应式数据
const data = reactive({
  tableData: [],  // 表格数据
  pageNum: 1,     // 当前页码
  pageSize: 10,   // 每页显示数量
  total: 0,       // 总记录数
  name: null,     // 搜索条件
  formVisible: false, // 表单显示状态
  form: {},       // 表单数据
  ids: [],        // 选中数据的ID
  productName: null,
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  operation:''
})


const load = () => {
  let params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    productName: data.productName,
  }
  loadSellerProductApi(params).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
      console.log(data.tableData)
    } else {
      ElMessage.error(res.msg)
    }
  })
}
load()

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
  data.operation ='edit'
  data.form.quantity = 1
}





// 重置筛选条件
const reset = () => {
  data.productName = null
  load()
}

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum
  load()
}
const handleSizeChange=(pageSize)=> {
  data.pageSize = pageSize
  load()
}
// 处理选中的行
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.sellerProductId)
}


const productForm = ref()
// 校验规则
const rules = {
  productName: [
    { required: true, message: '请输入药品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入药品价格', trigger: 'blur' },
  ],
  stockQuantity: [
    { required: true, message: '请输入药品库存', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入药品描述', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入药品类别', trigger: 'blur' }
  ],
  currentStock : [
    { required: true, message: '请输入当前库存', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入报损数量', trigger: 'blur' }
  ],
  reportCause: [
    { required: true, message: '请输入报损原因', trigger: 'blur' }
  ]

}
const handleImgSuccess = (res) => {
  data.form.imageUrl = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}

// 提交表单
const submitForm = () => {
  productForm.value.validate((valid) => {
    if (valid) {
     insertDamageReport()
    } else {
      ElMessage.error('请填写必须的参数！');
      return false;
    }
  });
}

//时间重塑，用于时间格式化，更新数据时记录
const formateDate =()=>{
  const date = new Date();  // 获取当前时间
  const year = date.getFullYear();  // 获取年份
  const month = String(date.getMonth() + 1).padStart(2, '0');  // 获取月份，注意需要 +1
  const day = String(date.getDate()).padStart(2, '0');  // 获取日期
  const hours = String(date.getHours()).padStart(2, '0');  // 获取小时
  const minutes = String(date.getMinutes()).padStart(2, '0');  // 获取分钟
  const seconds = String(date.getSeconds()).padStart(2, '0');  // 获取秒数

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const insertDamageReport = () => {
  let params = {
    productId: data.form.sellerProductId,
    quantity: data.form.quantity,
    reportCause: data.form.reportCause,
    reportTime: formateDate(),
    employeeName : data.user.name
  }
  console.log(params)
  insertDamageReportApi(params).then(res => {
    if (res.code === '200') {
      ElMessage.success('报损成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
</script>

<style scoped>
.el-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

.el-table td {
  padding: 12px 0;
}

.el-table .el-tag {
  margin: 2px;
}
/* 分页样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 订单详情Dialog */
.el-dialog {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-dialog__header {
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f5f7fa;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 24px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.close-button {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.close-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 退货Dialog */
.el-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-input, .el-textarea, .el-select {
  width: 100%;
  max-width: 600px;
}

.el-textarea__inner {
  border-radius: 8px;
  padding: 10px;
}

.el-select {
  width: 100%;
  max-width: 300px;
}

.el-button {
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #ffffff;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>